package com.ybdz.scanner.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.ybdz.scanner.R;
import com.ybdz.scanner.api.ApiStore;
import com.ybdz.scanner.base.BaseActivity;
import com.ybdz.scanner.bean.LuKuBean;
import com.ybdz.scanner.bean.InputBean;
import com.ybdz.scanner.bean.InputWeightBean;
import com.ybdz.scanner.event.ObjEvent;
import com.ybdz.scanner.utils.DialogUtil;
import com.ybdz.scanner.utils.KeyBoardUtil;
import com.ybdz.scanner.utils.ListUtil;
import com.ybdz.scanner.utils.MyToast;
import com.ybdz.scanner.utils.UIUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.view.KeyEvent.KEYCODE_NUMPAD_DOT;

/**
 * @ClassName: LuKuDetailActivity
 * @author: zhao
 * @Description: 录入重量
 * @date 2018/2/24 15:39
 */
public class LuKuDetailActivity extends BaseActivity {

    @BindView(R.id.ll_back)
    LinearLayout mLlBack;
    @BindView(R.id.home)
    FrameLayout mHome;
    @BindView(R.id.name)
    TextView mName;
    @BindView(R.id.place)
    TextView mPlace;
    @BindView(R.id.factory)
    TextView mFactory;
    @BindView(R.id.specification)
    TextView mSpecification;
    @BindView(R.id.weight)
    EditText mWeight;
    @BindView(R.id.checked)
    CheckBox mChecked;
    @BindView(R.id.rl_box)
    FrameLayout mRlBox;
    @BindView(R.id.save)
    Button mSave;
    @BindView(R.id.cancel)
    Button mCancel;
    @BindView(R.id.ll)
    RelativeLayout mLl;

    private String isConformity = "false";
    private InputBean.DataBean mData;
    private String scanResult;
    private Double mActualWeight;
    private String weight;
    private List<LuKuBean> mList = new ArrayList<>();
    private QMUIDialog.MessageDialogBuilder qmuiDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weight_input);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        //粗糙的实现在Editext获取焦点的情况下，点击其他地方隐藏输入框
        mLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InputMethodManager imm = (InputMethodManager)
                        getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null){
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);

                }
                mWeight.setCursorVisible(false);
            }
        });

        initData(mData);
        if (mActualWeight != null && mActualWeight > 0){
            mWeight.setText(String.valueOf(weight));
            setHint(weight);
        }else {
            mWeight.setText("");
        }
        //自动获取焦点代码；
        mWeight.setFocusable(true);
        mWeight.setFocusableInTouchMode(true);
        mWeight.requestFocus();

        //自定义键盘代码
        final KeyBoardUtil keyBoardUtil = new KeyBoardUtil(this);
        mWeight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                keyBoardUtil.attachTo(mWeight);
                mWeight.setFocusable(true);
                mWeight.setFocusableInTouchMode(true);
                mWeight.requestFocus();

            }
        });

        mWeight.addTextChangedListener(watch);
    }

    //增加输入监听，只能输入小数点后两位；
    private TextWatcher watch = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

           if (s.toString().contains(".")){
                mWeight.removeTextChangedListener(watch);
               String subMsg = s.toString().substring(s.toString().indexOf("."), s.toString().length());
               //操过小数点后两位，保留后两位；
               if (subMsg.length() > 3){
                   String newMsg = String.valueOf(s.toString().substring(0, s.toString().indexOf(".") + 3));
                   mWeight.setText(newMsg);
                   mWeight.setSelection(newMsg.length());
               }else {
                   mWeight.setText(s.toString());
                   mWeight.setSelection(s.toString().length());
               }
                mWeight.addTextChangedListener(watch);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };


    @OnClick({R.id.ll_back, R.id.home, R.id.save, R.id.cancel, R.id.weight})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_back:                      //返回
                finish();
                break;
            case R.id.home:                         //返回首页
                startActivity(new Intent(LuKuDetailActivity.this, MainActivity.class));
                finish();
                break;
            case R.id.save:                         //保存，提交数据到服务器
                String weight = mWeight.getText().toString().trim();    //获取用户录入的重量信息

                inputChaEDialog(LuKuDetailActivity.this,mWeight,"25kg",weight+"kg");


//                boolean checkWeight = checkWeight(weight);
//                if (checkWeight){
//                    inputWeightApi(weight);
//                }
                break;
            case R.id.cancel:                       //取消，关闭界面
                finish();
            case R.id.weight:                       //设置点击获取焦点，显示光标
                mWeight.setCursorVisible(true);
                break;
        }
    }

    //上下3公斤差额提示框；
    public void inputChaEDialog(final Activity activity, final EditText view, String guige, String weight){
        AlertDialog.Builder builder = new AlertDialog.Builder(activity, R.style.UpdateDialog);
        final AlertDialog dialog = builder.create();
        if (!activity.isFinishing()){
            dialog.show();
            Window window = dialog.getWindow();
            if (window != null){
                window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
                window.setContentView(R.layout.dialog_input_weight_confirm);
                TextView dialog_guige = (TextView) window.findViewById(R.id.dialog_guige);
                TextView dialog_weight = (TextView) window.findViewById(R.id.dialog_weight);
                Button btn_compelet = (Button) window.findViewById(R.id.btn_compelet);
                Button btn_input_again = (Button) window.findViewById(R.id.btn_input_again);
                dialog_guige.setText(String.valueOf(guige));
                dialog_weight.setText(String.valueOf(weight));
                btn_compelet.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                        String weight = mWeight.getText().toString().trim();    //获取用户录入的重量信息
                        boolean checkWeight = checkWeight(weight);
                        if (checkWeight){
                            inputWeightApi(weight);
                        }
                    }
                });

                btn_input_again.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                        view.setFocusable(true);
                        view.setFocusableInTouchMode(true);
                        view.requestFocus();
                    }
                });
            }
        }
    }

    //检测输入的重量是否合法；注意需要\\双斜杠转义；
    private boolean checkWeight(String weight) {
        String regex = "^[0-9]+(\\.[0-9]{1,2})?$";
        if (weight.length() == 0 ){
            MyToast.show(LuKuDetailActivity.this, "请输入重量!");
            return false;
        } else if (weight.contains(".") && weight.substring(weight.indexOf("."),weight.length()).length() > 3){
            MyToast.show(LuKuDetailActivity.this, "请精确到小数点后两位");
            return false;
        }else if (weight.matches(regex)){
            //避免0.00 0.0 等情况；
            double aDouble = Double.parseDouble(weight);
            if (aDouble > 0){
                return true;
            }else {
                MyToast.show(LuKuDetailActivity.this, "请输入重量!");
                return false;
            }
        }else if (weight.endsWith(".")){
            MyToast.show(LuKuDetailActivity.this,"不符合要求！");
            return false;
        }else if (weight.endsWith(".0")){
            return true;
        }else if (weight.endsWith(".00")){
            return true;
        }else {
            MyToast.show(LuKuDetailActivity.this,"不符合要求！");
            return false;
        }
    }

    /**
     * 提交重量的网络请求
     * @param weight
     */
    private void inputWeightApi(final String weight) {
        if (mChecked.isChecked()) {         //获取CheckBox的状态
            isConformity = "false";
        } else {
            isConformity = "true";
        }
        showLoading(LuKuDetailActivity.this);
        ApiStore.commitWeight(scanResult,weight,isConformity).enqueue(new Callback<InputWeightBean>() {
            @Override
            public void onResponse(Call<InputWeightBean> call, Response<InputWeightBean> response) {
                InputWeightBean body = response.body();
                if (body != null){
                    String code = body.getCode();
                    if (code != null && code.length() >0 ){
                        hideLoading();
                        if (code.equals("00")){
                            String productName = mData.getProductName();
                            LuKuBean historyBean = new LuKuBean(String.valueOf(productName==null?"":productName),String.valueOf(weight),String.valueOf(isConformity.equalsIgnoreCase("true")?"合格":"不合格"));
                            ListUtil.addLuKuList(historyBean);

                            MyToast.show(LuKuDetailActivity.this, "录入成功");

                            final String mDataProductName = mData.getProductName();
                            final String mDataSpecification = mData.getSpecification();
                            final int quantity = body.getQuantity(); //需要入库数量
                            final int scanQuantity = body.getScanQuantity(); //已入库数量
                            if (quantity == scanQuantity){
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        DialogUtil.luKuCompleteDialog(LuKuDetailActivity.this,String.valueOf(mDataProductName+"，"+mDataSpecification+"；"),String.valueOf("拟入库数量"+quantity+"，已入库数量"+scanQuantity));
                                    }
                                });
                            }else {
                                MyToast.show(LuKuDetailActivity.this, "录入成功");
                                LuKuDetailActivity.this.finish();
                            }

                        }else {
                            MyToast.show(LuKuDetailActivity.this,String.valueOf(body.getMsg()));
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<InputWeightBean> call, Throwable t) {
                    hideLoading();
                    onFailTimeOut(LuKuDetailActivity.this);
            }
        });
    }


    //EvnentBus接收上一个界面传递过来的对象信息
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void getEvent(InputBean depositEvent) {
        mData = depositEvent.getData();
        if (mData != null){
            weight = mData.getActualWeight();
            if (weight==null){
                mActualWeight=0.0;
            }else {
                mActualWeight = Double.parseDouble(weight);
            }
        }
    }

    //EvnentBus接收上一个界面传递过来的对象信息
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void getScanResult(ObjEvent responeEvent) {
        if (responeEvent.getId().equals("scanResult")) {
            scanResult = (String) responeEvent.getObj();
        }
    }

    /**
     * 设置数据
     *
     * @param data
     */
    private void initData(InputBean.DataBean data) {
        if (data != null){
            String productName = data.getProductName();
            if (productName == null || productName.equalsIgnoreCase("null")){
                mName.setText("");
            }else {
                mName.setText(String.valueOf( productName));
            }

            String origin = data.getOrigin();
            if (origin == null || origin.equalsIgnoreCase("null")){
                mPlace.setText("原产地：");
            }else {
                mPlace.setText(String.valueOf("原产地：" + origin));
            }

            String factoryNumber = data.getFactoryNumber();
            if (factoryNumber == null || factoryNumber.equalsIgnoreCase("null")){
                mFactory.setText("工厂厂号：");
            }else {
                mFactory.setText(String.valueOf("工厂厂号：" + factoryNumber));
            }

            String specification = data.getSpecification();
            if (specification == null || specification.equalsIgnoreCase("null")){
                mSpecification.setText("规格：");
            }else {
                mSpecification.setText(String.valueOf("规格：" + specification));
            }
        }

    }

    /**
     * 当重量不为null时，提示用户
     */
    private void setHint(final String weight) {
        final String isQualified = mData.getIsQualified();
        AlertDialog.Builder builder = new AlertDialog.Builder(LuKuDetailActivity.this,R.style.UpdateDialog);
        final AlertDialog dialog = builder.create();
        if (dialog.isShowing()){
            dialog.dismiss();
        }else {
            dialog.setCancelable(false);
            dialog.show();
            Window window = dialog.getWindow();
            if (window != null){
                window.setContentView(R.layout.dialog_put_weiht);
//                window.setLayout(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
                window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
                TextView queDing = (TextView) window.findViewById(R.id.btn_queding);
                TextView noticeMsg = (TextView) window.findViewById(R.id.tv_Msg);
                noticeMsg.setText(String.valueOf(UIUtils.getString(R.string.dialog)+weight+"kg，"+"是否重新编辑？"));
                TextView quXiao = (TextView) window.findViewById(R.id.btn_quxiao);
                quXiao.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                        LuKuDetailActivity.this.finish();
                    }
                });
                queDing.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mWeight.setSelection(weight.length());  //设置光标位置
                        if (isQualified.equals("false")) {
                            mChecked.setChecked(true);
                        } else {
                            mChecked.setChecked(false);
                        }
                        dialog.dismiss();
                    }
                });
            }
        }


//        if (qmuiDialog == null){
//            qmuiDialog = new QMUIDialog.MessageDialogBuilder(LuKuDetailActivity.this).
//                    setTitle(UIUtils.getString(R.string.hint))
//                    .setMessage(UIUtils.getString(R.string.dialog)+weight+"kg,"+"是否重新编辑？")
//                    .addAction(UIUtils.getString(R.string.cancel), new QMUIDialogAction.ActionListener() {
//                        @Override
//                        public void onClick(QMUIDialog dialog, int index) {
//                            dialog.dismiss();
//                            LuKuDetailActivity.this.finish();
//                        }
//                    })
//                    .addAction(0,UIUtils.getString(R.string.confirm), QMUIDialogAction.ACTION_PROP_NEGATIVE,new QMUIDialogAction.ActionListener() {
//                        @Override
//                        public void onClick(QMUIDialog dialog, int index) {
//                            mWeight.setSelection(weight.length());  //设置光标位置
//                            if (isQualified.equals("false")) {
//                                mChecked.setChecked(true);
//                            } else {
//                                mChecked.setChecked(false);
//                            }
//                            dialog.dismiss();
//                        }
//                    });
//            qmuiDialog.show();
//        }

//        new QMUIDialog.MessageDialogBuilder(LuKuDetailActivity.this)
//                .setTitle(UIUtils.getString(R.string.hint))
//                .setMessage(UIUtils.getString(R.string.dialog))
//                .addAction(UIUtils.getString(R.string.cancel), new QMUIDialogAction.ActionListener() {
//                    @Override
//                    public void onClick(QMUIDialog dialog, int index) {
//                        dialog.dismiss();
//                        LuKuDetailActivity.this.finish();
//                    }
//                })
//                .addAction(0,UIUtils.getString(R.string.confirm), QMUIDialogAction.ACTION_PROP_NEGATIVE,new QMUIDialogAction.ActionListener() {
//                    @Override
//                    public void onClick(QMUIDialog dialog, int index) {
//                        mWeight.setSelection(String.valueOf(weight).length());  //设置光标位置
//                        if (isQualified.equals("false")) {
//                            mChecked.setChecked(true);
//                        } else {
//                            mChecked.setChecked(false);
//                        }
//                        dialog.dismiss();
//                    }
//                })
//                .show();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    //目的输入点号；.
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_PERIOD){
            keyCode = KEYCODE_NUMPAD_DOT;
        }
        return super.onKeyDown(keyCode,event);
    }


}
